<script setup>
import { getListApi, addUserApi, editUserApi, deleteUserApi, getRoleListApi, getUserRoleApi } from '@/api/user'
import { reactive, ref, onMounted } from 'vue'
import { resetForm, objCoppy, myConfrim } from '@/utils'

// 表格内容
const tableData = ref([])
// 表格高度
const tableHeight = ref(0)

onMounted(() => {
    tableHeight.value = window.innerHeight - 220
})

// 获取表格数据绑定数据
const listParm = reactive({
    // 分页选中页
    currentPage: 1,
    // 默认每页的大小
    pageSize: 10,
    // 分页的总条数
    total: 0,
    nickName: '',
    phone: ''
})

// 弹窗属性
const dialog = reactive({
    title: '',
    visible: false,
    width: 630,
    height: 200
})

// 弹窗表单对象
const addRef = ref(null)

// 新增或者编辑表单数据绑定对象
const addModel = reactive({
    type: '0', // 区分是新增还是编辑 0: 新增 1: 编辑
    userId: '',
    nickName: '',
    phone: '',
    email: '',
    sex: '',
    username: '',
    password: '',
    roleId: ''
})

// 角色列表
const roleList = ref([])

// 表单校验规则
const rules = {
    nickName: [
        {
            trigger: 'blur',
            required: true,
            message: '请填写姓名'
        }
    ],
    phone: [
        {
            trigger: 'blur',
            required: true,
            message: '请填写电话'
        }
    ],
    email: [
        {
            trigger: 'blur',
            required: true,
            message: '请填写邮箱'
        }
    ],
    sex: [
        {
            trigger: 'blur',
            required: true,
            message: '请选择性别'
        }
    ],
    roleId: [
        {
            trigger: 'change',
            required: true,
            message: '请选择角色'
        }
    ],
    username: [
        {
            trigger: 'blur',
            required: true,
            message: '请填写账户'
        }
    ],
    password: [
        {
            trigger: 'blur',
            required: true,
            message: '请填写密码'
        }
    ]
}

// 获取表格数据
const getList = async () => {
    const res = await getListApi(listParm)
    tableData.value = res.data.records
    listParm.total = res.data.total
}

getList()

// 获取角色列表
const getRoleList = async () => {
    const res = await getRoleListApi()
    roleList.value = res.data
}

getRoleList()

// 搜索按钮
const searchBtn = () => getList()

// 重置按钮
const resetBtn = () => {
    // 清空上一次的搜索表单
    listParm.nickName = ''
    listParm.phone = ''
    // 刷新表格
    getList()
}

// 新增按钮
const addBtn = () => {
    dialog.title = '新增用户'
    dialog.visible = true
    // 清空上一次的表单
    resetForm(addRef.value, addModel)
    // 设置为新增模式
    addModel.type = '0'
}

// 编辑按钮
const editBtn = async (row) => {
    dialog.title = '编辑用户'
    // 清空上一次的表单
    resetForm(addRef.value, addModel)
    // 把当前要编辑的数据复制到表单数据域
    objCoppy(row, addModel)
    // 获取用户的角色
    const res = await getUserRoleApi({ userId: row.userId })
    // 把获取到的角色信息保存
    addModel.roleId = res.data?.roleId
    // 设置为新增模式
    addModel.type = '1'
    dialog.visible = true
}

// 删除按钮
const deleteBtn = async (row) => {
    const confirm = await myConfrim("确定要删除该用户吗?")
    if (confirm) {
        const res = await deleteUserApi({ userId: row.userId })
        // 刷新表格
        getList()
        // 消息提示
        ElMessage({
            message: res.msg,
            type: 'success'
        })
    }
}

// 分页大小改变时触发
const sizeChange = (val) => {
    listParm.pageSize = val
    getList()
}
// 分页页数改变时触发
const currentChange = (val) => {
    listParm.currentPage = val
    getList()
}

// 弹窗确认
const onConfirm = async () => {
    await addRef.value.validate(async (valid) => {
        if (valid) {
            let res = null
            if (addModel.type === '0') {
                // 新增
                res = await addUserApi(addModel)
            } else if (addModel.type === '1') {
                res = await editUserApi(addModel)
            }
            // 刷新表格
            getList()
            // 消息提示
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            dialog.visible = false
        }
    })
}

// 弹窗取消
const onClose = () => dialog.visible = false
</script>

<template>
    <!-- 搜索区域 -->
    <el-form :model="listParm" label-width="80px" :inline="true">
        <el-form-item>
            <el-input placeholder="请输入姓名" v-model="listParm.nickName"></el-input>
        </el-form-item>
        <el-form-item>
            <el-input placeholder="请输入电话" v-model="listParm.phone"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button icon="Search" @click="searchBtn">搜索</el-button>
            <el-button icon="Close" style="color: #ff7670;" @click="resetBtn">重置</el-button>
            <el-button v-permission="['sys:user:add']" icon="Plus" type="primary" @click="addBtn">新增</el-button>
        </el-form-item>
    </el-form>
    <!-- 表格区域 -->
    <el-table :height="tableHeight" :data="tableData" border stripe>
        <el-table-column prop="nickName" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column v-permission="['sys:user:edit', 'sys:user:delete']" fixed="right" label="操作" width="160"
            align="center">
            <template #default="scope">
                <div flex>
                    <el-button type="primary" icon="Edit" size="small" @click="editBtn(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="Delete" size="small" @click="deleteBtn(scope.row)">删除</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page.sync="listParm.currentPage"
        :page-sizes="[10, 20, 40, 80, 100]" :page-size="listParm.pageSize" layout="total,sizes,prev,pager,next,jumper"
        :total="listParm.total" background>
    </el-pagination>
    <!-- 弹窗区域 -->
    <el-dialog v-model="dialog.visible" :width="dialog.width" :close-on-click-modal="false">
        <template #header>
            <h1>{{ dialog.title }}</h1>
        </template>
        <div :style="{ height: dialog.height + 'px' }">
            <el-form :model="addModel" ref="addRef" :rules="rules" label-width="80px" mr-8>
                <el-row>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="nickName" label="姓名">
                            <el-input v-model="addModel.nickName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="phone" label="电话">
                            <el-input v-model="addModel.phone"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="email" label="邮箱">
                            <el-input v-model="addModel.email"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="sex" label="性别">
                            <el-radio-group v-model="addModel.sex">
                                <el-radio :label="'0'">男</el-radio>
                                <el-radio :label="'1'">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="roleId" label="角色">
                            <el-select v-model="addModel.roleId" placeholder="请选择角色">
                                <el-option v-for="i in roleList" :key="i.roleId" :label="i.roleName" :value="i.roleId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="username" label="账户">
                            <el-input v-model="addModel.username"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col v-if="addModel.type == 0" :span="12" :offset="0">
                        <el-form-item prop="password" label="密码">
                            <el-input v-model="addModel.password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button type="primary" @click="onConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>